using System;
using System.Collections;
using System.Web.UI;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.SearchContext;

namespace PHSRAG.Insight21.Common.Reports
{
    public partial class SqlReportHost : BasePage
    {
        private const string RequestParamNameFormat = "fmt";
        private const string RequestParamNameReport = "rpt";
        private const string RequestParamNamePageUrl = "pageUrl";
        private const string ConfigKeyWebUrl = "weburl";

        #region Overrides of Page

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event to initialize the page.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            Load += OnPageLoad;
            base.OnInit(e);
        }

        #endregion

        protected void OnPageLoad(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (string.IsNullOrEmpty(Request[RequestParamNameReport])) return;

            UserContext userContext = (UserContext)Session[UserContext.CacheKey];
            Hashtable sqlReportParams = (Session[Constants.SessionVarNameSsrsReportParams] as Hashtable) ?? new Hashtable();

            sqlReportParams.Remove(SSRSRequest.ReportParameterKeys.DomainUserId);
            sqlReportParams.Add(SSRSRequest.ReportParameterKeys.DomainUserId, userContext.DomainUserId.ToString());
            sqlReportParams.Remove(SSRSRequest.ReportParameterKeys.UserName);
            sqlReportParams.Add(SSRSRequest.ReportParameterKeys.UserName, userContext.LastName + ", " + userContext.FirstName);

            Policy.ICachePolicy cachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];

            sqlReportParams.Remove(SSRSRequest.ReportParameterKeys.FilterCriteria);
            sqlReportParams.Add(SSRSRequest.ReportParameterKeys.FilterCriteria, GetFilterCriteriaForReport(cachePolicy));
            sqlReportParams.Remove(SSRSRequest.ReportParameterKeys.WebUrl);
            sqlReportParams.Add(SSRSRequest.ReportParameterKeys.WebUrl, Utility.Settings.GetKeyValue(ConfigKeyWebUrl, string.Empty));

            SSRSRequest.FetchAndDisplayReport(Request[RequestParamNameFormat], Request[RequestParamNameReport], sqlReportParams);
        }

        private string GetFilterCriteriaForReport(Policy.ICachePolicy cachePolicy)
        {
            CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;

            if (searchContext != null)
            {
                SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Request[RequestParamNamePageUrl]);
                return searchCriteria.ToString(";");
            }

            return string.Empty;
        }
    }
}